package aszm.chahaospider.parser.chahao;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import aszm.chahaospider.parser.chahao.bean.Tmp_City;
import aszm.chahaospider.utils.MybatisUtils;
import aszm.chahaospider.utils.Utils;
import chaohao.mybatis.dao.PhoneHomeDtoMapper;
import chaohao.mybatis.model.ISPDto;
import chaohao.mybatis.model.PhoneHomeDto;

public class PhoneHomeParser {
	private static final Logger Log = Logger.getLogger(PhoneHomeParser.class.getName());

	public static void getNumberFromWeb(Tmp_City city, List<ISPDto> isps, boolean writeDb) {
		try {
			Log.info("20s后开始抓取……");
			Thread.sleep(20 * 1000);
		} catch (InterruptedException e) {
		}
		Document doc = Utils.getDocumentDoc(city.getUrl());
		Elements links = doc.select("li a");
		if (writeDb) {
			Log.info("共" + links.size() + "条" + city.getCity() + "开始写入 ……");
			createFile(links, city, isps);
		} else {
			parserNumber(links, city, isps);
		}
	}

	private static void createFile(Elements links, Tmp_City city, List<ISPDto> isps) {
		SqlSession session = MybatisUtils.getSqlSession();
		int count = 0;
		for (Element link : links) {
			PhoneHomeDto phoneNumber = parser(link, city, isps);
			session.getMapper(PhoneHomeDtoMapper.class).insert(phoneNumber);
			if (count % 2000 == 0) {
				session.commit();
				session.close();
				session = MybatisUtils.getSqlSession();
			}
			count++;
		}
		session.commit();
		MybatisUtils.closeSession(session);
		Log.info(count + "条" + city.getCity() + "写入成功!");

	}

	private static PhoneHomeDto parser(Element link, Tmp_City city, List<ISPDto> isps) {
		PhoneHomeDto phoneNumber = new PhoneHomeDto();
		String number = link.html();
		for (ISPDto isp : isps) {
			if (isp.getNumber().equals(number.substring(0, 4))) {
				phoneNumber.setIsp(isp.getName());
				phoneNumber.setIspId(isp.getId());
				phoneNumber.setIspNumber(isp.getNumber());
			} else if (isp.getNumber().equals(number.substring(0, 3))) {
				phoneNumber.setIsp(isp.getName());
				phoneNumber.setIspId(isp.getId());
				phoneNumber.setIspNumber(isp.getNumber());
			}
		}
		phoneNumber.setProvice(city.getProvice());
		phoneNumber.setCity(city.getCity());
		phoneNumber.setNumber(number);
		// Log.info(phoneNumber.toString());
		return phoneNumber;
	}

	private static List<PhoneHomeDto> parserNumber(Elements links, Tmp_City city, List<ISPDto> isps) {
		List<PhoneHomeDto> tb_Locations = new ArrayList<PhoneHomeDto>();
		for (Element link : links) {
			PhoneHomeDto phoneNumber = parser(link, city, isps);
			tb_Locations.add(phoneNumber);
		}
		return tb_Locations;
	}
}
